package com.edushare.common.dao;

import java.util.HashMap;
import java.util.List;

import org.apache.cayenne.DataObjectUtils;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.query.SelectQuery;

import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.GroupMembers;
import com.edushare.common.vo.Groups;
import com.edushare.common.vo.Users;

public class GroupsDAO extends CayenneBasedDAO {

	public GroupsDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}

	public Groups getGroupById(int groupId) {
		return DataObjectUtils.objectForPK(getDataContext(), Groups.class, groupId);
	}

	public void createNewGroup(Groups group) {
		getDataContext().registerNewObject(group);
		getDataContext().commitChanges();
		new GroupsMembersDAO(ormInterface).addNewMember(group, group.getCreator(), GroupMembers.GROUP_ADMIN, GroupMembers.STATUS_ACTIVE);
	}

	public List<Groups> getMyGroups(Users user) {
		Expression exp = Expression.fromString("groupMember.user = $usr and groupMember.status = $stts");
		HashMap<String, Object> hm = new HashMap<String, Object>();
		hm.put("usr", user);
		hm.put("stts", GroupMembers.STATUS_ACTIVE);
		SelectQuery query = new SelectQuery(Groups.class, exp.expWithParameters(hm));
		return getDataContext().performQuery(query);
	}
	
	public void deleteGroup(Groups group){
		List<GroupMembers> members = group.getGroupMember();
		getDataContext().deleteObjects(members);		
		getDataContext().deleteObject(group);
		getDataContext().commitChanges();
	}

}
 